import MySQLdb
from loguru import logger
from com.arcfox.util import constant


def __connect_db():
    return MySQLdb.connect(constant.DB_HOST, constant.DB_USER_NAME, constant.DB_PASSWORD, constant.DB_NAME,
                           charset='utf8')


def open_and_close_db(func):
    def wrapper(*a, **k):
        conn = __connect_db()
        cursor = conn.cursor()
        try:
            result = func(*a, **k, cursor=cursor)
            conn.commit()
        except Exception as e:
            logger.warning(e)
        finally:
            if conn:
                conn.close()
        return result
    return wrapper

def async_open_and_close_db(func):
    async def wrapper(*a, **k):
        conn = __connect_db()
        cursor = conn.cursor()
        # logger.info(f"[{func.__name__}]打开db连接")
        try:
            result = await func(*a, **k, cursor=cursor)
            conn.commit()
        finally:
            if conn:
                conn.close()
                logger.info(f"[{func.__name__}]关闭db连接")
        return result

    return wrapper

@open_and_close_db
def save_or_update(sql, cursor):
    logger.info(sql)
    cursor.execute(sql)


@open_and_close_db
def delete(sql, cursor):
    logger.info(sql)
    cursor.execute(sql)


@open_and_close_db
def truncate(table, cursor):
    sql = f"truncate table {table}"
    logger.warning(table)
    cursor.execute(sql)


@open_and_close_db
def query_all(sql, cursor):
    logger.info(sql)
    cursor.execute(sql)
    return cursor.fetchall()


@open_and_close_db
def query_one(sql, cursor):
    logger.info(sql)
    cursor.execute(sql)
    return cursor.fetchone()

